"""扫描记录Repository"""
from typing import Optional, List, Dict, Any
from sqlalchemy.orm import Session
from sqlalchemy import and_
from app.models.scan_record import ScanRecord
from app.repositories.base import BaseRepository


class ScanRecordRepository(BaseRepository[ScanRecord]):
    """扫描记录数据访问层"""

    def __init__(self, db: Session):
        super().__init__(ScanRecord, db)

    def get_by_task_id(
        self,
        task_id: int,
        skip: int = 0,
        limit: int = 100,
        order_by: Optional[str] = None,
    ) -> List[ScanRecord]:
        """根据任务ID获取扫描记录列表"""
        return self.get_all(
            skip=skip,
            limit=limit,
            filters={"task_id": task_id},
            order_by=order_by or "scan_time desc",
        )

    def get_by_branch(self, branch: str, task_id: Optional[int] = None) -> List[ScanRecord]:
        """根据分支获取扫描记录"""
        query = self.db.query(ScanRecord).filter(ScanRecord.branch == branch)
        if task_id:
            query = query.filter(ScanRecord.task_id == task_id)
        return query.order_by(ScanRecord.scan_time.desc()).all()

    def get_latest_by_task(self, task_id: int) -> Optional[ScanRecord]:
        """获取任务的最新扫描记录"""
        return (
            self.db.query(ScanRecord)
            .filter(ScanRecord.task_id == task_id)
            .order_by(ScanRecord.scan_time.desc())
            .first()
        )

